package com.wzh.mall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @program: mall
 * @description: 登录
 * @author: Mr.Wang
 * @create: 2021-10-09 08:25
 **/
@Controller
public class LoginController {


    @Autowired
    StringRedisTemplate redisTemplate;




    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){

        String s = redisTemplate.opsForValue().get(token);
        return s;
    }


    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url,Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token){
        if (sso_token!=null){
            // 说明之前有人登陆过 在浏览器留下了痕迹

            return  "redirect:"+url+"?tocken="+sso_token;
        }

        model.addAttribute("url",url);

        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String name,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response){

        if (!StringUtils.isEmpty(name)&&!StringUtils.isEmpty(password)){
            // 登陆成功
            // 把登陆成功的用户保存起来
            String uuid= UUID.randomUUID().toString().replace("-","");
            redisTemplate.opsForValue().set(uuid,name);

            Cookie sso_token = new Cookie("sso_token",uuid);
            response.addCookie(sso_token);

            return "redirect:"+url+"?tocken="+uuid;
        }
        //登陆失败 展示登录页
        return "login";
    }

}
